package com.andy.process.fork;

import com.andy.common.entity.Bean;
import com.andy.common.entity.Field;
import com.andy.common.entity.Schema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * Created by Administrator on 2017/9/6.
 */
public class ParserTask extends RecursiveTask<List<Bean>> {
    private static final Logger LOG = LoggerFactory.getLogger(ParserTask.class);
    private List<String> lines;
    private Schema schema;
    private List<Field> fields;
    private List<Bean> Beans;
    private String[] name;
    private Object[] value;
    private AtomicInteger totalCount;
    private AtomicInteger successCount;

    public ParserTask(List<String> line, Schema configuration) {
        this.lines = line;
        this.schema = configuration;
        fields = this.schema.getFields();
        Beans = new ArrayList<>();
        totalCount = new AtomicInteger(0);
        successCount = new AtomicInteger(0);
    }

    protected List<Bean> compute() {
        for (int i = 0; i < lines.size(); i++) {
            String part = lines.get(i);
            String[] params = part.split("\n");
            for (int j = 1; j < params.length; j++) {
                //统计
                totalCount.incrementAndGet();
                String currentLine = params[j];
                String[] param = currentLine.split(",");
                if (param.length != fields.size()) {
                    LOG.error("current line size is not equals field Size, the line is:{} the fields size is:{}", param.length, fields.size());
                    LOG.error("missing param line is ->" + currentLine);
                    continue;
                }
                successCount.incrementAndGet();
                Bean bean = new Bean();
                name = new String[fields.size()];
                value = new Object[fields.size()];
                for (int k = 0; k < param.length; k++) {
                    for (Field field : fields) {
                        if (k == field.getIndex())
                            transformData(name, value, param[k], field);
                    }
                }
                bean.setName(name);
                bean.setValue(value);
                Beans.add(bean);
            }
        }
        LOG.info("total row is:{} and success get row is:{}", totalCount.get(), successCount.get());
        return Beans;
    }

    /**
     * transform value into correct value
     *
     * @param bean
     * @param name
     * @param value
     * @param s
     * @param field
     */
    private void transformData(String[] name, Object[] value, String s, Field field) {
        name[field.getIndex()] = field.getName();
        value[field.getIndex()] = s;
    }

}
